// pages/iq-test/iq-test.js
import { UploadImg } from '../../common/utils/index'
import { UPLOAD_IMAGE_URL, ERR_OR } from '../../common/config.js'
const { request, token, c_id, message, router } = global;
const pixelRatio = wx.getSystemInfoSync().pixelRatio
Page({

  /**
   * 页面的初始数据
   */
  data: {
    count: 0,
    countTimer: null,
    path: '',
    id: '',
    showLine: false,
    isUnderfined: -1,
    dots: [],
    content: '',
    score: 0,
    area: [],
    isSucc: true,
    shareImg: '',
    getShareImgError: true,
    saveImgDots: [],
    saveImgArea: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let path = options.path;
    let id = options.id
    this.setData({
      path,
      id
    })
    this._uploadImg()
    // this.getAiResult(uuid)
  },
  _uploadImg() {
    const that = this
    let path = this.data.path
    let id = this.data.id
    that.setData({
      showLine: true
    })
    wx.uploadFile({
      url: UPLOAD_IMAGE_URL, //仅为示例，非真实的接口地址
      filePath: path,
      name: 'file',
      formData: {
        'file': path,
        'token': token,
        'companyId': c_id,
        'productId': id
      },
      success(res) {
        that.setData({
          showLine: false
        })
        const data = JSON.parse(res.data)
        if (data.status == 1) {
          const resMsg = JSON.parse(data.resMsg)
          resMsg.points.map((item) => {
            item.x = (item.x) / pixelRatio
            item.y = (item.y) / pixelRatio
          })
          resMsg.area.map((item) => {
            item.x = (item.x) / pixelRatio
            item.y = (item.y) / pixelRatio
          })
          that.setData({
            dots: resMsg.points,
            content: resMsg.content,
            score: resMsg.score,
            area: resMsg.area
          })
          that.drawDot()
          that.countInterval()
          that.getSaveImgDot(resMsg.points, resMsg.area)
        } else {
          that.setData({
            isUnderfined: 0
          })
        }
        //do something
      }
    })
  },
  handleBack() {
    this.setData({
      isUnderfined: 0
    })
    router.back(1)
  },
  getSaveImgDot(dots, area) {
    let saveImgDots = JSON.parse(JSON.stringify(dots))
    let saveImgArea = JSON.parse(JSON.stringify(area))
    saveImgDots.map((item) => {
      item.x = (item.x) * 17 / 28 + 54
      item.y = (item.y) * 17 / 28 + 131
    })
    saveImgArea.map((item) => {
      item.x = (item.x) * 17 / 28 + 54
      item.y = (item.y) * 17 / 28 + 131
    })
    this.setData({
      saveImgDots,
      saveImgArea
    })
    this.createdCode()
  },
  createdCode() {
    let that = this;
    let { score, path, content, saveImgDots, saveImgArea } = that.data
    console.log(saveImgArea)
    // saveImgArea = this.initializeArea(saveImgArea)
    let verticalLineWidth = saveImgArea[0].y - saveImgArea[1].y;
    let middleLineWidth = saveImgArea[2].x - saveImgArea[1].x;
    const detail = this.data.detail;
    const ctx = wx.createCanvasContext('shareFrends');
    ctx.drawImage('../../assets/result_bg.png', 0, 0, 286, 485);
    ctx.drawImage('../../assets/score.png', 43, 30, 200, 70);
    ctx.setFontSize(20)
    ctx.setTextAlign('center');
    ctx.setFillStyle('white');
    ctx.fillText(score, 143, 78)
    ctx.setStrokeStyle('#ff6a9d')
    ctx.strokeRect(53, 130, 173, 173)
    ctx.drawImage(path, 54, 131, 171, 171);
    ctx.drawImage('../../assets/bg.png', 43, 120, 220, 214);

    for (let i = 0; i < saveImgDots.length; i++) {
      ctx.beginPath()
      ctx.arc(saveImgDots[i].x, saveImgDots[i].y, 1, 0, 2 * Math.PI)
      ctx.setFillStyle('rgba(0,250,154,0.6)')
      ctx.fill()
    }
    let gradient = ctx.createLinearGradient(200, 100, 100, 200);
    gradient.addColorStop("0", "#2661DD");
    gradient.addColorStop("0.5", "#40ED94");
    gradient.addColorStop("1.0", "#5956CC");
    ctx.setLineWidth(2);
    ctx.setStrokeStyle(gradient);
    console.log(saveImgArea)
    console.log(saveImgArea[1].x)
    console.log(saveImgArea[1].y)
    console.log(middleLineWidth)
    console.log(verticalLineWidth)
    ctx.strokeRect(saveImgArea[1].x, saveImgArea[1].y, middleLineWidth, verticalLineWidth)


    ctx.setFontSize(12);
    
    ctx.setFillStyle('black');

    let canvasWidth = 240; //画布宽度
    let startLocation = 0;
    let textareaWidth = Math.ceil(canvasWidth / 12); //画布宽度除以字号
    if (content.length > textareaWidth) {
      ctx.setTextAlign('left');
      startLocation = 23
    } else {
      ctx.setTextAlign('center');
      startLocation = 143
    }
    for (let i = 0; i < content.length; i++) {
      let text = content.substr(0, textareaWidth);
      content = content.substr(textareaWidth, content.length)
      ctx.fillText(text, startLocation, 355 + (16 * i))
    }
    // ctx.fillText(`${content}`, 143, 350)
    ctx.drawImage(global.qrCode.path, 53, 390, 50, 50);
    ctx.drawImage(global.logo.path, 183, 390, 50, 50);
    ctx.setFillStyle('white');
    ctx.setFontSize(10)
    ctx.setTextAlign('center');
    ctx.fillText('扫一扫或长按二维码进入小程序', 122, 460)
    ctx.draw()
    this.saveCanvasImg()
  },
  saveCanvasImg() {
    const that = this
    setTimeout(() => {
      // 将生成的canvas图片，转为真实图片
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        canvasId: 'shareFrends',
        success: function (res) {
          let shareImg = res.tempFilePath;
          that.setData({
            shareImg: shareImg
          })
          console.log(shareImg)
        },
        fail: function (res) {
          that.setData({
            getShareImgError: true
          })
        }
      })
    }, 500)
  },
  handleSaveCanvasImage() {
    const { shareImg, getShareImgError } = this.data
    if (getShareImgError) {
      if (shareImg) {
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.writePhotosAlbum']) {
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  wx.saveImageToPhotosAlbum({
                    filePath: shareImg,
                    success() {
                      message.tips('保存图片成功')
                    },
                    fail() {
                      message.tips('保存图片失败，请稍后再试~')
                    }
                  })
                }
              })
            } else {
              // 有则直接保存
              wx.saveImageToPhotosAlbum({
                filePath: shareImg,
                success() {
                  message.tips('保存图片成功')
                },
                fail() {
                  message.tips('保存图片失败，请稍后再试~')
                }
              })
            }
          }
        })
      } else {
        this.saveCanvasImg()
        message.tips('图片生成中，请稍后再试~')
      }
    } else {
      message.tips('下载图片失败，请稍后再试~')
    }
    
  },
  onShareAppMessage: function (res) {
    console.log(this.data.content)
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    return {
      title: this.data.content,
      path: '/pages/index/index?scene=' + global.c_id
    }
  },
  drawDot: function() {
    const dots = this.data.dots;
    var ctx = wx.createCanvasContext('canvasProgressbg');
    let dotsLength = dots.length;
    let count = 0
    let countTimer = setInterval(() => {
      if (count < dotsLength) {
        for (let i = 0; i < dotsLength; i++) {
          if (i > count) {
            break;
          }
          ctx.beginPath()
          ctx.arc(dots[i].x, dots[i].y, 1, 0, 2 * Math.PI)
          ctx.setFillStyle('rgba(0,250,154,0.6)')
          ctx.fill()
        }
        ctx.draw()
        count++
      } else {
        clearInterval(countTimer);
      }
    }, 100)
    // Draw points
    
  },
  drawRect: function (areaData, num) {
    var context = wx.createCanvasContext('canvasProgress');
    var gradient = context.createLinearGradient(200, 100, 100, 200);
    gradient.addColorStop("0", "#2661DD");
    gradient.addColorStop("0.5", "#40ED94");
    gradient.addColorStop("1.0", "#5956CC");
    context.setLineWidth(2);
    context.setStrokeStyle(gradient);
    let verticalLineWidth = areaData[0].y - areaData[1].y;
    let middleLineWidth = areaData[2].x - areaData[1].x;
    let totalNum = Math.ceil((verticalLineWidth + middleLineWidth) * 2);//总边长
    let verticalLineScale = verticalLineWidth / totalNum * 100
    var perNum = totalNum / 100;
    //num%所占的长度
    var nal = perNum * num; //每一个格子占多少
    if (num <= verticalLineScale) {
      context.moveTo(areaData[0].x, areaData[0].y)
      context.lineTo(areaData[1].x, areaData[0].y - nal);
      context.stroke();
      context.draw()
    } else if (num <= 50) {
      nal = perNum * (num - verticalLineScale); //每一个格子占多少
      let end = (areaData[1].x + nal) > areaData[2].x ? areaData[2].x : (areaData[1].x + nal)
      context.moveTo(areaData[0].x, areaData[0].y)
      context.lineTo(areaData[1].x, areaData[1].y)
      context.lineTo(end, areaData[2].y)
      context.stroke();
      context.draw()
    } else if (num <= 50 + verticalLineScale) {
      nal = perNum * (num - 50); //每一个格子占多少
      context.moveTo(areaData[0].x, areaData[0].y)
      context.lineTo(areaData[1].x, areaData[1].y)
      context.lineTo(areaData[2].x, areaData[2].y)
      context.lineTo(areaData[3].x, areaData[2].y + nal)
      context.stroke();
      context.draw()
    } else if (num <= 100) {
      nal = perNum * (num - 50 - verticalLineScale); //每一个格子占多少
      let end = (areaData[2].x - nal) < areaData[1].x ? areaData[1].x : (areaData[2].x - nal)
      context.moveTo(areaData[0].x, areaData[0].y)
      context.lineTo(areaData[1].x, areaData[1].y)
      context.lineTo(areaData[2].x, areaData[2].y)
      context.lineTo(areaData[3].x, areaData[3].y)
      context.lineTo(end, areaData[0].y)
      context.stroke();
      context.draw()
    }
  },
  initializeArea: function(area) {
    var tmp = area[2];
    area.splice(2, 1)
    area.unshift(tmp)
    return area
  },
  countInterval: function () { // 设置倒计时 定时器 每100毫秒执行一次，计数器count+1
    let area = this.data.area;
    const areaData = this.initializeArea(area)
    let count = 0;
    let countTimer = setInterval(() => {
      if (count <= 100) {
        count++
        this.drawRect(areaData, count)
      } else {
        clearInterval(countTimer);
        this.setData({
          isSucc: false
        })
      } 
    }, 50)
  },
// { "points": [{ "x": 54, "y": 73 }, { "x": 80, "y": 58 }, { "x": 105, "y": 44 }, { "x": 129, "y": 34 }, { "x": 150, "y": 44 }, { "x": 93, "y": 102 }, { "x": 93, "y": 99 }, { "x": 104, "y": 93 }, { "x": 109, "y": 97 }, { "x": 102, "y": 95 }, { "x": 99, "y": 103 }, { "x": 104, "y": 102 }, { "x": 118, "y": 63 }, { "x": 122, "y": 83 }, { "x": 130, "y": 99 }, { "x": 137, "y": 82 }, { "x": 136, "y": 70 }, { "x": 146, "y": 74 }, { "x": 151, "y": 82 }, { "x": 145, "y": 80 }, { "x": 140, "y": 90 }, { "x": 152, "y": 85 }, { "x": 132, "y": 113 }, { "x": 139, "y": 110 }, { "x": 144, "y": 112 }, { "x": 135, "y": 125 }, { "x": 143, "y": 127 }, { "x": 154, "y": 123 }, { "x": 149, "y": 132 }, { "x": 112, "y": 153 }, { "x": 118, "y": 154 }, { "x": 128, "y": 150 }, { "x": 136, "y": 148 }, { "x": 150, "y": 142 }, { "x": 153, "y": 138 }, { "x": 165, "y": 138 }, { "x": 172, "y": 139 }, { "x": 174, "y": 133 }, { "x": 123, "y": 162 }, { "x": 138, "y": 163 }, { "x": 142, "y": 168 }, { "x": 154, "y": 162 }, { "x": 159, "y": 156 }, { "x": 163, "y": 148 }, { "x": 166, "y": 146 }, { "x": 156, "y": 167 }], "area": [{ "x": 59, "y": 27 }, { "x": 178, "y": 27 }, { "x": 59, "y": 173 }, { "x": 178, "y": 173 }], "score": "100", "content": "åºé¨æ³å¤èµ°å æ­¥é½å¥½é¾ï¼æ»æäººå²çä½ å¤§åï¼æè¦çå®" }
  getAiResult(uuid) {
    let inter = setInterval(() => {
      request.post('/api/core/003-getAiResult', {
        uuid,
        pageNo: 1,
        limit: 10
      }).then((res) => {
        const data = res.data
        if (data.code === ERR_OR) {
          if (data.rows[0].status) {
            clearInterval(inter)
          }
        }
      }).catch((err) => {
        console.log(err)
      })
    }, 1000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.drawProgressbg()
    // this.drawRect(100)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})